package service

import (
	"context"
	v1 "gitee.com/jacktuotuo/coolcar/api/user/service/v1"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// Login 登录
func (s *UserService) Login(ctx context.Context, in *v1.LoginRequest) (*v1.LoginReply, error) {

	openId, err := s.uc.OpenIdResolver(in.Code)
	if err != nil {
		return nil, status.Errorf(codes.Unavailable, "can not resolve openId: %v", err)
	}

	id, err := s.uc.QueryAccountId(ctx, openId)
	if err != nil {
		return nil, status.Errorf(codes.Unavailable, "can not find accountId: %v", err)
	}

	var token, expiresTime, e = s.uc.GenerateToken(id)

	if e != nil {
		return nil, status.Errorf(codes.Unavailable, "can not find accountId: %v", e)
	}

	return &v1.LoginReply{
		AccessToken: token,
		ExpiresIn:   expiresTime,
	}, nil
}
